// index.js
const App = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stations: [],
    sourceStations: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.stations = App.HttpResource('/stations/')
  },

  initData: function () {
    this.stations.queryAsync()
    .then(data => {
      data.unshift({id: 0, name: '全部待派送订单', address: ''})
      this.setData({ stations: data, sourceStations: data })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initData()
  },

  fuzzySearch: function (event) {
    let searchStations = []
    let sourceStations = this.data.sourceStations
    if (event.detail.value) {
      sourceStations.forEach(station => {
        if (station.name.indexOf(event.detail.value) >= 0) {
          searchStations.push(station)
        }
      })
    } else {
      searchStations = sourceStations
    }
    this.setData({ stations: searchStations })
  },
  
  navigateTo: function (event) {
    let selectedStation = event.currentTarget.dataset.station
    App.WxService.setStorageSync('selectedStation', selectedStation)
    if (App.WxService.getStorageSync('token')) {
      let user = App.WxService.getStorageSync('user')
      user.user_profile.station = selectedStation
      App.WxService.setStorageSync('user', user)
    }
    wx.reLaunch({ url: '/pages/index/index' })
  }
})